module.exports = options => {
  const jwt = require('jsonwebtoken')
  const assert = require('http-assert')
  const AdminUser = require('../models/AdminUser')

  return async(req, res, next) => {
    const token = String(req.headers.authorization || '').split(' ').pop()
    assert(token, 401, '请先登录') // 没有token
    let info
    jwt.verify(token, req.app.get('secret'), (err, token) => {
      assert(token, 401, '非法登录') // 非法token
      info = token
    })
    req.user = await AdminUser.findById(info.id)
    assert(req.user, 401, '登陆失败')
    await next()
  }
}